﻿using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace supermarket
{
    public partial class shopTJ : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        private readonly string _tip;
        public shopTJ (string tip)
        {
            InitializeComponent();
            _tip = tip;
        }


        private void shopTJ_Load ( object sender, EventArgs e )
        {
            LoadSalesRecords(dgv_SalesRecords, _tip);
            DrawDailySalesChart(chartSales, _tip);
        }

        private void btnmuban_Click ( object sender, EventArgs e )
        {
            try
            {
                DialogResult result = MessageBox.Show("是否下载店铺管理模板？", "提示",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    string templatePath = Path.Combine(Application.StartupPath, "DataTemplate", "店铺管理模板.xlsx");

                    if (!File.Exists(templatePath))
                    {
                        MessageBox.Show("模板文件不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "Excel Files|*.xlsx";
                    saveFileDialog.Title = "保存模板文件";
                    saveFileDialog.FileName = "店铺管理模板.xlsx";

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        File.Copy(templatePath, saveFileDialog.FileName, true);
                        MessageBox.Show("模板下载成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"下载模板时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExport_Click ( object sender, EventArgs e )
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel Files|*.xlsx";
                openFileDialog.Title = "选择要导入的Excel文件";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;
                    DataTable dt = ExcelHelperNew.ImportFromExcel(filePath);

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        MessageBox.Show("Excel文件中没有数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 开始导入数据
                    if (sql.State != ConnectionState.Open)
                    {
                        sql.Open();
                    }

                    using (SqlTransaction transaction = sql.BeginTransaction())
                    {
                        try
                        {
                            string insertQuery = @"INSERT INTO SalesRecords 
                                (shop_code, shop_name, customer_name, customer_phone, 
                                sale_amount, sale_date, payment_method, items_purchased) 
                                VALUES 
                                (@shop_code, @shop_name, @customer_name, @customer_phone, 
                                @sale_amount, @sale_date, @payment_method, @items_purchased)";

                            using (SqlCommand cmd = new SqlCommand(insertQuery, sql, transaction))
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    cmd.Parameters.Clear();
                                    cmd.Parameters.AddWithValue("@shop_code", row["门店编码"] ?? DBNull.Value);
                                    cmd.Parameters.AddWithValue("@shop_name", _tip); // 使用当前店铺名称
                                    cmd.Parameters.AddWithValue("@customer_name", row["顾客姓名"] ?? DBNull.Value);
                                    cmd.Parameters.AddWithValue("@customer_phone", row["联系电话"] ?? DBNull.Value);
                                    cmd.Parameters.AddWithValue("@sale_amount", Convert.ToDecimal(row["收款金额"]));
                                    cmd.Parameters.AddWithValue("@sale_date", Convert.ToDateTime(row["销售日期"]));
                                    cmd.Parameters.AddWithValue("@payment_method", row["支付方式"] ?? DBNull.Value);
                                    cmd.Parameters.AddWithValue("@items_purchased", row["商品详情"] ?? DBNull.Value);

                                    cmd.ExecuteNonQuery();
                                }
                            }

                            transaction.Commit();
                            MessageBox.Show($"成功导入 {dt.Rows.Count} 条销售记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 刷新销售记录显示
                            LoadSalesRecords(dgv_SalesRecords, _tip);
                            // 刷新销售图表
                            DrawDailySalesChart(chartSales, _tip);
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"导入数据时发生错误：{ex.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        /// <summary>
        /// 加载销售记录到DataGridView（固定查询SalesRecords表）
        /// </summary>
        /// <param name="dgv">要绑定数据的DataGridView控件</param>
        public void LoadSalesRecords ( DataGridView dgv, string tip )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string query = @"SELECT*FROM [super].[dbo].[SalesRecords] 
                WHERE [shop_name] = @tip
                ORDER BY [record_id] DESC";

                DataTable dataTable = new DataTable();

                using (SqlCommand command = new SqlCommand(query, sql))
                {
                    command.Parameters.AddWithValue("@tip", tip);

                    using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dataTable);
                    }
                }

                dgv.DataSource = dataTable;

                dgv.Columns["shop_code"].HeaderText = "门店编码";
                dgv.Columns["shop_name"].HeaderText = "门店名称";
                dgv.Columns["customer_name"].HeaderText = "顾客姓名";
                dgv.Columns["customer_phone"].HeaderText = "联系电话";
                dgv.Columns["sale_amount"].HeaderText = "收款金额";
                dgv.Columns["sale_date"].HeaderText = "销售日期";
                dgv.Columns["payment_method"].HeaderText = "支付方式";
                dgv.Columns["items_purchased"].HeaderText = "商品详情";

                if (dgv.Columns.Contains("sale_date"))
                {
                    dgv.Columns["sale_date"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
                }

                if (dgv.Columns.Contains("sale_amount"))
                {
                    dgv.Columns["sale_amount"].DefaultCellStyle.Format = "C2";
                    dgv.Columns["sale_amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                }

                dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载销售记录失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        public void DrawDailySalesChart ( Chart chartControl, string tip )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string query = @"SELECT 
                CAST([sale_date] AS DATE) AS SaleDate,
                SUM([sale_amount]) AS DailyTotal
                FROM [super].[dbo].[SalesRecords]
                WHERE [shop_name] = @tip
                GROUP BY CAST([sale_date] AS DATE)
                ORDER BY SaleDate";

                DataTable dataTable = new DataTable();

                using (SqlCommand command = new SqlCommand(query, sql))
                {
                    command.Parameters.AddWithValue("@tip", tip);

                    using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dataTable);
                    }
                }

                chartControl.Series.Clear();
                chartControl.Titles.Clear();
                chartControl.Annotations.Clear();

                chartControl.Titles.Add($"每日销售额趋势图 - {tip}");
                chartControl.Titles[0].Font = new Font("Microsoft YaHei", 12, FontStyle.Bold);

                Series series = new Series("每日销售额");
                series.ChartType = SeriesChartType.Line;
                series.BorderWidth = 3;
                series.Color = Color.SteelBlue;
                series.MarkerStyle = MarkerStyle.Circle;
                series.MarkerSize = 8;
                series.MarkerColor = Color.Red;
                series.IsValueShownAsLabel = true;
                series.LabelFormat = "C2";
                series.Font = new Font("Microsoft YaHei", 8);
                series.LabelForeColor = Color.DarkBlue;
                series.XValueType = ChartValueType.Date;

                foreach (DataRow row in dataTable.Rows)
                {
                    DateTime date = Convert.ToDateTime(row["SaleDate"]);
                    decimal total = Convert.ToDecimal(row["DailyTotal"]);

                    DataPoint point = new DataPoint();
                    point.SetValueXY(date.ToOADate(), total);
                    point.ToolTip = $"{date:yyyy-MM-dd}\n销售额: {total:C2}";
                    point.Label = total.ToString("C2");
                    series.Points.Add(point);
                }
                chartControl.Series.Add(series);

                ChartArea chartArea = chartControl.ChartAreas[0];
                chartArea.AxisX.Title = "日期";
                chartArea.AxisX.TitleFont = new Font("Microsoft YaHei", 10);
                chartArea.AxisX.LabelStyle.Format = "MM-dd";
                chartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
                chartArea.AxisX.Interval = 1;
                chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
                chartArea.AxisX.MajorTickMark.Interval = 1;

                chartArea.AxisY.Title = "销售额";
                chartArea.AxisY.TitleFont = new Font("Microsoft YaHei", 10);
                chartArea.AxisY.LabelStyle.Format = "C0";
                chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;

                chartArea.AxisX.LabelStyle.Angle = -45;
                chartArea.AxisX.LabelStyle.Interval = 1;

                chartArea.CursorX.IsUserEnabled = true;
                chartArea.CursorX.IsUserSelectionEnabled = true;
                chartArea.AxisX.ScaleView.Zoomable = true;
                chartArea.AxisY.ScaleView.Zoomable = true;

                chartControl.BackColor = Color.WhiteSmoke;
                chartArea.BackColor = Color.White;
                chartArea.ShadowColor = Color.Transparent;

                chartArea.AxisX.IsLabelAutoFit = true;
                chartArea.AxisY.IsLabelAutoFit = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成图表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

    }
}
